package com.virus.server.test;

import com.virus.server.utils.FileUtils;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyClassLoader extends ClassLoader {

    private File testDirectory = new File(System.getProperty("user.dir"), "TestDirectory");

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name) throws ClassNotFoundException {
        String fileName = name.replace(".", "/") + ".class";
        File file = new File(testDirectory, fileName);
        if (!file.exists()){
            throw new ClassNotFoundException("the class [" + fileName + "] can not be found");
        }
        return FileUtils.getBytes(file);
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> aClass = myClassLoader.loadClass("com.virus.server.test.TestClassLoader");
        Object o = aClass.newInstance();
        Method start = aClass.getMethod("start");
        start.invoke(o);
    }
}
